package com.company.psm.controller;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.company.psm.entity.User;
import com.company.psm.service.StoreManagement;
import com.company.psm.service.UserManagement;
import com.company.psm.util.Util;

@Controller
@RequestMapping("/account")
public class UserController {
	@Autowired
	private UserManagement userManagement;
	@Autowired
	private StoreManagement storeManagement;
	@RequestMapping(method=RequestMethod.GET,value = "list")
	public ModelAndView getAllUser(@RequestParam(value="listAll", required=false) String listAll,
			@RequestParam(value="searchKey", required=false) String searchKey,
			@RequestParam(value="roleName", required=false) String role
			){
		List<User> users = new ArrayList<User>();
		ModelAndView model = new ModelAndView();
		model.addObject("stores",storeManagement.getAll());
		if (listAll!=null && listAll.equals("listAllData")){
				users = userManagement.getAllUser();
		}else{
			if (searchKey!=null){
				System.err.println("SEARCHKEY = " + searchKey);
				users = userManagement.search(searchKey);
				model.addObject("searchKey",searchKey);
			}else if(role!=null){
				users = userManagement.searchRole(role, "0");
				model.addObject("role",role);
			}
		}
		model.addObject("users",users);
		model.setViewName("/account/list");
		return model;
	}
	
	@RequestMapping(value = "create",method = RequestMethod.GET)
	public ModelAndView addUser(@RequestParam(value="username", required=false) String userName,
			@RequestParam(value="fullname", required=false) String fullname,
			@RequestParam(value="password", required=false) String password,
			@RequestParam(value="roleId", required=false) String roleId,
			@RequestParam(value="email", required=false) String email,
			@RequestParam(value="storeId",required=false) String store){
		ModelAndView model = new ModelAndView();
		model.addObject("users",userManagement.getAllUser());
		if(userName != null){
			userManagement.addUser(fullname,userName, Util.encryptMD5(password), roleId, email, store);
			model.setViewName("/account/list");
		}else{
			model.setViewName("/account/create");
		}
		return model;
	}
	@RequestMapping(method=RequestMethod.GET, value = "delete")
	public ModelAndView delete(@RequestParam(value="userId", required=false) String userId){
		try{
			userManagement.deleteUser(Long.parseLong(userId));
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		return new ModelAndView("/account/list", "users", userManagement.getAllUser());
	}
	
	@RequestMapping(method=RequestMethod.GET, value = "update")
	public ModelAndView edit(
			@RequestParam(value="userId", required=false) String userId,
			@RequestParam(value="fullname", required=false) String fullname,
			@RequestParam(value="username", required=false) String userName,
			@RequestParam(value="password", required=false) String pass,
			@RequestParam(value="roleId", required=false) String roleId,
			@RequestParam(value="email", required=false) String email){
		System.err.println("UserID=" + userId);
		if(userId != null){
			userId = String.valueOf(userId).split(",")[0];
			userManagement.updateUser(userId,fullname,userName,Util.encryptMD5(pass), roleId, email);
		}
		return new ModelAndView("/account/list", "users", userManagement.getAllUser());
	}
	
	@RequestMapping(method=RequestMethod.GET, value = "detail")
	public ModelAndView detail(
			@RequestParam(value="userId", required=false) String userId){
		if(userId != null){
			userManagement.getUserById(Long.parseLong(userId));
			return new ModelAndView("/account/edit", "users", userManagement.getUserById(Long.parseLong(userId)));
		}else{
			return new ModelAndView("/account/list", "users", userManagement.getAllUser());
		}
	}
	
	@RequestMapping(method=RequestMethod.GET,value = "search")
	public @ResponseBody String getSearchUser(@RequestParam(value="searchKey", required=false) String searchKey){
		List<User> users = userManagement.searchRole(searchKey,"0");
	    JSONObject responseDetailsJson = new JSONObject();
	    JSONArray jsonArray = new JSONArray();
	    JSONObject formDetailsJson = new JSONObject();
	    for (User user : users) {
	        formDetailsJson = new JSONObject();
	        formDetailsJson.put("id", user.getId());
	        formDetailsJson.put("password", user.getPassword());
	        formDetailsJson.put("fullname", user.getFullname());
	        formDetailsJson.put("account", user.getAccount());
	        formDetailsJson.put("role", user.getRole().getName());
	        formDetailsJson.put("email", user.getEmail());
	        jsonArray.put(formDetailsJson);
		}
	    responseDetailsJson.put("forms", jsonArray);
	    return jsonArray.toString();
	}
	
	@RequestMapping(method=RequestMethod.GET,value = "auth")
	public  @ResponseBody String getRole(){
	      Authentication authentication = SecurityContextHolder.getContext().
	    		  getAuthentication();
	    		  String name = authentication.getName();
	      JSONObject responseDetailsJson = new JSONObject();
		  JSONArray jsonArray = new JSONArray();
		  JSONObject formDetailsJson = new JSONObject();
		        formDetailsJson = new JSONObject();
		        formDetailsJson.put("role",userManagement.getUserByAccount(name).getRole().getName());
		        formDetailsJson.put("name",name);
		        jsonArray.put(formDetailsJson);
		    responseDetailsJson.put("forms", jsonArray);
		    return jsonArray.toString();
	}
    public User getCurrentUser(){
    	Authentication authentication = SecurityContextHolder.getContext().
      		  getAuthentication();
      		  String name = authentication.getName();
      	return userManagement.getUserByAccount(name);
    }
    
	@RequestMapping(method=RequestMethod.GET,value = "checkDuplicate")
    public Boolean checkDuplicate(@RequestParam(value="account", required=false) String account){
    	List<User> users = new ArrayList<User>();
    	users = userManagement.getAllUser();
		ModelAndView model = new ModelAndView();
		model.addObject("stores",storeManagement.getAll());
		boolean check = true;
		for (User user : users) {
			if (account!=null && account.equals(user.getAccount()) ){
				check = false;
			}
		}
		return check;
    }
}
